<?php
/**
 * Created by PhpStorm.
 * User: lzy
 * Date: 2018/2/1 0001
 * Time: 11:40
 */

namespace App\Base\Exceptions;


class ApiException extends \Exception
{

    const DEFAULT_ERROR_CODE = 500;

    const DEFAULT_ERROR_MESSAGE = '服务器忙，请稍候重试...';

    const ERROR_NOT_FOUND = [404, '请求的页面不存在'];

    const ERROR_AUTHORIZATION = [403, '认证失败'];

    const ERROR_VALIDATION = [422, '验证不通过'];

    const ERROR_DATABASE = [1000, '数据库执行异常'];

    const ERROR_UPLOAD_QINIU = [1001, '上传文件失败'];

    const ERROR_HTTP_ERROR = [1002, '获取数据失败'];

    const ERROR_NOT_ENABLE = [1003,'功能暂未开启'];

    const ERROR_ACCESS_NOT_ENABLE = [403,'403禁止访问'];

    const ERROR_UNAUTHORIZE_ACCESS = [601,'访问未授权'];

    const ERROR_NOT_EXCEPTION = [500, '请求系统异常'];

    const ERROR_SEND_MESSAGE = [1004, '发送短信失败:{msg}'];

    const ERROR_CHECK_MOBILE_MESSAGE = [1000, '手机验证码错误'];

    /**
     * ApiException constructor.
     * @param array $error
     * @param array $params 参数
     */
    public function __construct($error, $params = [])
    {
        $code = $error[0] ?? self::DEFAULT_ERROR_CODE;
        $msg = $error[1] ?? self::DEFAULT_ERROR_MESSAGE;
        $msg = $this->handleMsg($msg,$params);
        parent::__construct($msg, $code);
    }

    /**
     * 解析msg
     * @param string $msg  --- 错误信息:{message}
     * @param array $params --- {"message":"您访问的页面不存在"}
     * @return string
     */
    private function handleMsg($msg, $params)
    {
        foreach ($params as $key => $item) {
            $msg = str_replace('{' . $key . '}', $item, $msg);
        }
        return $msg;
    }


}